<?php
namespace User\Controller;
use Think\Controller;
class CommissionController extends Controller {

    //获取返佣数据的父级
    public function getRebate($arr,$agent){
        foreach($arr as $k => $v){
            if($v['user_id']==$agent){
                if($v['position']==1){
                    return $this->getRebate($arr,$v['user_recommend']);
                }else{
                    return array('user_id'=>$v['user_id'],'group'=>$v['group'],'position'=>$v['position']);
                }
            }
        }
    }

    //获取下线层级
    public function getChildsClass($data,$uid,$arr,$n){
        $n++;
        foreach ($data as $k => $v){
            if($uid==$v['user_recommend']){
                $v['class']=$n;
                $arr[]=$v;
                unset($data[$k]);
                $arr=$this->getChildsClass($data,$v['user_id'],$arr,$n);
            }
        }
        return $arr;
    }
    //获取下线层级,一层
    public function getChildsClass1($data,$uid,$arr,$n){
        $n++;
        foreach ($data as $k => $v){
            if($uid==$v['user_recommend']){
                $v['class']=$n;
                $arr[]=$v;
                unset($data[$k]);
                if($v['position']==1){
                    $arr=$this->getChildsClass1($data,$v['user_id'],$arr,$n);
                }
            }
        }
        return $arr;
    }

    //佣金明细
    public function detail(){
        $user=session('user');
        if(empty($user['user_id'])){
            $this->error('无效的登陆信息');
        }
        $from=I('from') ? I('from') : 0;
        $to=I('to') ? I('to') : 0;
        $child2=$child=I('child') ? I('child') : 0;
        if(!empty($from) && !empty($to)){
            $userModel=M('user');
            $userAll=$userModel->field('user_id,user_recommend,group,position')->where('(user_id='.$user['user_id'].') or ((user_role=1) and (user_recommend > 0))')->select();
            $childrenFile='Uploads/getChildsClass1/'.date('Ymd').'-'.$user['user_id'].'.txt';
            if(file_exists($childrenFile)){//判断更新缓存
                $children=file_get_contents($childrenFile);
                $children=unserialize($children);
            }else{
                set_time_limit(120);//程序执行时间
                $children= $this->getChildsClass1($userAll,$user['user_id'],[],0);//print_r($children);die;
                $childrenData=serialize($children);
                file_put_contents($childrenFile,$childrenData);
                // $this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
            }
            //print_r($children);die;
            if(!empty($child)){//筛选所需要查询的用户
                $childArr=explode(',',$child);
                $child=[];
                $childs=[];
                foreach ($children as $k => $v){
                    $childs[]=$v['user_id'];
                }
                foreach ($childArr as $k => $v){
                    if(in_array($v,$childs)){
                        $child[]=$v;
                    }
                }
            }else{
                $child=[];
                foreach ($children as $k => $v){
                    $child[]=$v['user_id'];
                }
            }
            if(empty($child)){
                $this->error('没有找到相关下线用户信息');
            }
            $userMember=[];//获取组装所有用户信息
            foreach ($userAll as $ke => $va){
                $userMember[$va['user_id']]=$va;
            }
            $section=C('section');//获取号段
            $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';
            $where.=' and (CLOSE_TIME between \''.$from.'\' and \''.$to.' 23:59:59'.'\') ';
            $where.=' and (LOGIN in ('.implode(',',$child).')) and (right(SYMBOL,2) = \'bo\') ';
            $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//            if($user['type']==1){
//                $model = M('mt4_trades', '', 'DB_CONFIG3');//数字
//            }else{
//                $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//            }

            //ini_set('memory_limit', '1280M');//查询量大时使用，内存设置
            $count=$model->where($where)->count();
            $Page=new \Think\Page($count,20);
            $Page->parameter['child']=$child2;
            $Page->parameter['from']=$from;
            $Page->parameter['to']=$to;
            $show=$Page->show();
            $reoups=$model->field('LOGIN,VOLUME')->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();
            if(empty($reoups)){
                $this->error('未找到交易记录');
            }

            $group=M('mt4_groups')->field('mt4_group,ratio')->select();
            $ratio=[];//每个组别的佣金比率
            foreach ($group as $k => $v){
                $ratio[$v['mt4_group']]=$v['ratio'];
            }
            $list=[];
            foreach ($reoups as $k => $v){
                $v['money']=$ratio[$userMember[$v['login']]['group']]*intval($v['volume']/100);
                $v['userinfo']=$userMember[$v['login']];
                $list[]=$v;
            }





            $this->assign('list',$list);// 赋值数据集
            $this->assign('page',$show);
            $this->assign('from',$from);
            $this->assign('to',$to);
            $this->display();
        }else{
            $this->display();
        }
    }
    //佣金明细-1层佣金
    public function searchDetail1(){
        $user=session('user');
        if(empty($user['user_id'])){
            $this->error('无效的登陆信息','detail');
        }
        $from=I('post.fo') ? I('post.fo') : 0;
        $to=I('post.to') ? I('post.to') : 0;
        $child=I('post.child') ? I('post.child') : 0;

        $userModel=M('user');
        $userAll=$userModel->field('user_id,user_recommend,group,position')->where('(user_id='.$user['user_id'].') or ((user_role=1) and (user_recommend > 0))')->select();
        $childrenFile='Uploads/getChildsClass1/'.date('Ymd').'-'.$user['user_id'].'.txt';
        if(file_exists($childrenFile)){//判断更新缓存
            $children=file_get_contents($childrenFile);
            $children=unserialize($children);
        }else{
            set_time_limit(120);//程序执行时间
            $children= $this->getChildsClass1($userAll,$user['user_id'],[],0);//print_r($children);die;
            $childrenData=serialize($children);
            file_put_contents($childrenFile,$childrenData);
           // $this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
        }
        //print_r($children);die;
        if(!empty($child)){//筛选所需要查询的用户
            $childArr=explode(',',$child);
            $child=[];
            $childs=[];
            foreach ($children as $k => $v){
                $childs[]=$v['user_id'];
            }
            foreach ($childArr as $k => $v){
                if(in_array($v,$childs)){
                    $child[]=$v;
                }
            }
        }else{
            $child=[];
            foreach ($children as $k => $v){
                $child[]=$v['user_id'];
            }
        }
        if(empty($child)){
            $this->error('没有找到相关下线用户信息','detail');
            //$this->ajaxReturn(array('status'=>0,'msg'=>'没有找到相关下线用户信息'));
            }
        $userMember=[];//获取组装所有用户信息
        foreach ($userAll as $ke => $va){
            $userMember[$va['user_id']]=$va;
        }
        $section=C('section');//获取号段
        $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';
        if(!empty($from) && !empty($to)){
            $where.=' and (CLOSE_TIME between \''.$from.'\' and \''.$to.'\') ';
        }
        $where.=' and (LOGIN in ('.implode(',',$child).')) and (right(SYMBOL,2) = \'bo\') ';
        //ini_set('memory_limit', '1280M');//查询量大时使用，内存设置
        $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        if($user['type']==1){
//            $model = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }
        $count=$model->where($where)->count();
        $Page=new \Think\Page($count,20);
        $Page->parameter['child']=$child;
        $Page->parameter['from']=$from;
        $Page->parameter['to']=$to;
        $show=$Page->show();
        $reoups=$model->field('LOGIN,VOLUME')->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        if(empty($reoups)){
            //$this->ajaxReturn(array('status'=>0,'msg'=>'未找到交易记录'));
            $this->error('未找到交易记录','detail');
        }
        $group=M('mt4_groups')->field('mt4_group,ratio')->select();
        $ratio=[];//每个组别的佣金比率
        foreach ($group as $k => $v){
            $ratio[$v['mt4_group']]=$v['ratio'];
        }
        $list=[];
        foreach ($reoups as $k => $v){
            $v['money']=$ratio[$userMember[$v['login']]['group']]*intval($v['volume']/100);
            $v['userinfo']=$userMember[$v['login']];
            $list[]=$v;
        }
        //print_r($list);die;
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);
        $this->display('detail');
    }
    //佣金明细-2层佣金
    public function searchDetail2(){
        $user=session('user');
        if(empty($user['user_id'])){
            $this->ajaxReturn(array('status'=>0,'msg'=>'无效的登陆信息，请重新登陆'));
        }
        $from=I('post.from') ? I('post.from') : '2017-01-01';
        $to=I('post.to') ? I('post.to') : '2017-12-11';
        $child=I('post.child') ? I('post.child') : 0;
        $userModel=M('user');
        $userAll=$userModel->field('user_id,user_recommend,group,position')->where('(user_id='.$user['user_id'].') or ((user_role=1) and (user_recommend > 0))')->select();
        $childrenFile='Uploads/getChildsClass/'.date('Ymd').'-'.$user['user_id'].'.txt';
        if(file_exists($childrenFile)){//判断更新缓存
            $children=file_get_contents($childrenFile);
            $children=unserialize($children);
        }else{
            set_time_limit(120);//程序执行时间
            $children= $this->getChildsClass($userAll,$user['user_id'],[],0);//print_r($children);die;
            $childrenData=serialize($children);
            file_put_contents($childrenFile,$childrenData);
            $this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
        }
        //print_r($children);die;
        if(!empty($child)){//筛选所需要查询的用户
            $childArr=explode(',',$child);
            $child=[];
            $childs=[];
            foreach ($children as $k => $v){
                $childs[]=$v['user_id'];
            }
            foreach ($childArr as $k => $v){
                if(in_array($v,$childs)){
                    $child[]=$v;
                }
            }
        }else{
            $child=[];
            foreach ($children as $k => $v){
                $child[]=$v['user_id'];
            }
        }
        //print_r($child);die;
        if(empty($child)){$this->ajaxReturn(array('status'=>0,'msg'=>'没有找到相关下线用户信息'));}
        $userMember=[];//获取组装所有用户信息
        foreach ($userAll as $ke => $va){
            $userMember[$va['user_id']]=$va;
        }
        $section=C('section');//获取号段
        $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';
        if(!empty($from) && !empty($to)){
            $where.=' and (CLOSE_TIME between \''.$from.'\' and \''.$to.'\') ';
        }
        $where.=' and (LOGIN in ('.implode(',',$child).')) and (right(SYMBOL,2) = \'bo\') ';
        //ini_set('memory_limit', '1280M');//查询量大时使用，内存设置
        $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        if($user['type']==1){
//            $model = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }
        $count=$model->where($where)->count();
        $Page=new \Think\Page($count,25);
        $Page->parameter['child']=$child;
        $Page->parameter['from']=$from;
        $Page->parameter['to']=$to;
        $show=$Page->show();
        $reoups=$model->field('LOGIN,VOLUME')->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        if(empty($reoups)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'未找到交易记录'));
        }
        $rebateData=[];//最终需要返佣的数据-明细
        set_time_limit(120);//程序执行时间
        foreach ($reoups as $k => $v){
            $v['user_recommend']=$userMember[$v['login']]['user_recommend'];
            $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
            $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
            if(!empty($parents)){
                $parents2=$parents;
                foreach($parents2 as $ke => $va){
                    $flag=0;
                    foreach($parents as $key => $val){
                        if($va['position']==$val['position']){
                            $flag++;
                            if($flag>2){
                                unset($parents[$key]);
                            }
                        }
                    }
                }
                $v['parents']=$parents;//筛选出有返佣父级的数据
                $rebateData[]=$v;
                /*foreach ($parents as $k2 => $v2){
                    if($v2['user_id']==$user['user_id']){
                        $parents2=$parents;
                        foreach($parents2 as $ke => $va){
                            $flag=0;
                            foreach($parents as $key => $val){
                                if($va['position']==$val['position']){
                                    $flag++;
                                    if($flag>2){
                                        unset($parents[$key]);
                                    }
                                }
                            }
                        }
                        $v['parents']=$parents;//筛选出有返佣父级的数据
                        $rebateData[]=$v;break;
                    }
                }*/
            }
        }
        //print_r($rebateData);die;
        if(empty($rebateData)){$this->ajaxReturn(array('status'=>0,'msg'=>'未获取到佣金信息'));}
        $position=M('position')->field('id,ratio')->select();
        $pos=[];
        foreach($position as $k => $v){
            $pos[$v['id']]=$v['ratio'];
        }
        $list=[];
        foreach ($rebateData as $k => $v){
            $dat['login']=$v['login'];
            $dat['volume']=$v['volume']=intval($v['volume']/100);
            $dat['parent']=$user['user_id'];
            $dat['money']=0;
            foreach ($v['parents'] as $ke => $va){
                $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                if($ke>0){
                    $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                    if($ratio>0){
                        $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                    }else if($ratio==0){
                        $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=0;
                    }
                }else{
                    $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                }
                if($va['user_id']==$user['user_id']){
                    $dat['money']=$rebateData[$k]['parents'][$ke]['money'];
                }
            }
            $list[]=$dat;
        }
        print_r($list);die;
        $this->display();
    }
    //佣金明细-3层佣金
    public function searchDetail3(){
        $user=session('user');
        if(empty($user['user_id'])){
            $this->error('无效的登陆信息','detail');//$this->ajaxReturn(array('status'=>0,'msg'=>'无效的登陆信息，请重新登陆'));
        }
        $from=I('post.from') ? I('post.from') : '2018-01-01';
        $to=I('post.to') ? I('post.to') : '2018-12-11';
        $child2=$child=I('post.child') ? I('post.child') : 0;
        $userModel=M('user');
        $userAll=$userModel->field('user_id,user_recommend,group,position')->where('(user_id='.$user['user_id'].') or ((user_role=1) and (user_recommend > 0))')->select();
        $childrenFile='Uploads/getChildsClass/'.date('Ymd').'-'.$user['user_id'].'.txt';
        if(file_exists($childrenFile)){//判断更新缓存
            $children=file_get_contents($childrenFile);
            $children=unserialize($children);
        }else{
            set_time_limit(120);//程序执行时间
            $children= $this->getChildsClass($userAll,$user['user_id'],[],0);//print_r($children);die;
            $childrenData=serialize($children);
            file_put_contents($childrenFile,$childrenData);
            //$this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
        }
        //print_r($children);die;
        if(!empty($child)){//筛选所需要查询的用户
            $childArr=explode(',',$child);
            $child=[];
            $childs=[];
            foreach ($children as $k => $v){
                $childs[]=$v['user_id'];
            }
            foreach ($childArr as $k => $v){
                if(in_array($v,$childs)){
                    $child[]=$v;
                }
            }
        }else{
            $child=[];
            foreach ($children as $k => $v){
                $child[]=$v['user_id'];
            }
        }
        //print_r($child);die;
        if(empty($child)){
            //$this->ajaxReturn(array('status'=>0,'msg'=>'没有找到相关下线用户信息'));
            $this->error("没有找到相关下线用户信息",'detail');
           }
        $userMember=[];//获取组装所有用户信息
        foreach ($userAll as $ke => $va){
            $userMember[$va['user_id']]=$va;
        }
        $section=C('section');//获取号段
        $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';
        if(!empty($from) && !empty($to)){
            $where.=' and (CLOSE_TIME between \''.$from.'\' and \''.$to.' 23:59:59\') ';
        }else{
            $this->error("时间不可为空",'detail');
        }
        $where.=' and (LOGIN in ('.implode(',',$child).')) ';
        //ini_set('memory_limit', '1280M');//查询量大时使用，内存设置
        $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        if($user['type']==1){
//            $model = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }
        $count=$model->where($where)->count();
        $Page=new \Think\Page($count,20);
        $Page->parameter['child']=$child2;
        $Page->parameter['from']=$from;
        $Page->parameter['to']=$to;
        $show=$Page->show();
        $reoups=$model->field('LOGIN,VOLUME,SYMBOL')->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        if(empty($reoups)){
            $this->error("未找到交易记录",'detail');
        }
		//品种点差
		$spreadData=M('symbol_spread')->field('id,symbol,spread')->select();
		$spread=[];
		foreach($spreadData as $k => $v){
			$spread[$v['symbol']]=$v['spread'];
		}
        $rebateData=[];//最终需要返佣的数据-明细
        set_time_limit(120);//程序执行时间
        foreach ($reoups as $k => $v){
            $v['user_recommend']=$userMember[$v['login']]['user_recommend'];
            $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
            $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
            if(!empty($parents)){
                $parents2=$parents;
                foreach($parents2 as $ke => $va){
                    $flag=0;
                    foreach($parents as $key => $val){
                        if($va['position']==$val['position']){
                            $flag++;
                            if($flag>2){
                                unset($parents[$key]);
                            }
                        }
                    }
                }
				$v['spread']=$spread[$v['symbol']];
                $v['parents']=$parents;//筛选出有返佣父级的数据
                $rebateData[]=$v;
            }
        }
//        if(empty($rebateData)){
//            echo "<script>alert('未获取到佣金信息')</script>";$this->display('detail');exit;//$this->ajaxReturn(array('status'=>0,'msg'=>'未获取到佣金信息'));
//        }
        $position=M('position')->field('id,ratio,ratio_foreign')->select();
        $pos=[];//返佣比率
        $foreign=[];//外用比率
        foreach($position as $k => $v){
            $pos[$v['id']]=$v['ratio'];
            $foreign[$v['id']]=$v['ratio_foreign'];
        }
        $list=[];
		
		//print_r($rebateData);
        foreach ($rebateData as $k => $v){
            $dat['login']=$v['login'];
            $dat['symbol']=$v['symbol'];
            $dat['volume']=$v['volume']=round($v['volume']/100,2);
            $dat['parent']=$user['user_id'];
            $dat['money']=0;
            if(substr($v['symbol'],-2)=='bo'){
                foreach ($v['parents'] as $ke => $va){
                    $parent_arr[]=$va['user_id'];
                    $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                    if($ke>0){
                        $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                        if($ratio>0){
                            $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                        }else if($ratio==0){
                            $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                        }else{
                            $rebateData[$k]['parents'][$ke]['money']=0;
                        }
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                    }
                    if($va['user_id']==$user['user_id']){
                        $dat['money']=$rebateData[$k]['parents'][$ke]['money'];break;
                    }
                }
            }else{
                foreach ($v['parents'] as $ke => $va){
                    $parent_arr[]=$va['user_id'];
                    $rebateData[$k]['parents'][$ke]['ratio']=$foreign[$va['position']];
                    if($ke>0){
                        $ratio=$foreign[$va['position']]-$foreign[$v['parents'][$ke-1]['position']];
                        if($ratio>0){
                            $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume']*$v['spread'];
                        }else if($ratio==0){
                            $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                        }else{
                            $rebateData[$k]['parents'][$ke]['money']=0;
                        }
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=$foreign[$va['position']]*$v['volume']*$v['spread'];
                    }
                    if($va['user_id']==$user['user_id']){
                        $dat['money']=$rebateData[$k]['parents'][$ke]['money'];break;
                    }
                }
            }
            $list[]=$dat;
        }

        $this->assign('page',$show);
        $this->assign('list',$list);
        $this->display('detail');
    }
    //佣金汇总
    public function summary(){

        $this->display();
    }
    //获所有下级，只有账号
    public function getChilds($data,$uid,$arr){
        foreach ($data as $k => $v){
            if($uid==$v['user_recommend']){
                unset($data[$k]);
                $arr[]=$v['user_id'];
                $arr=$this->getChilds($data,$v['user_id'],$arr);
            }
        }
        return $arr;
    }
    //佣金汇总-1层佣金
    public function searchSummary1(){
        $user=session('user');
        if(empty($user['user_id'])){
            $this->error("无效的登陆信息，请重新登陆");
        }
        $from=I('post.from') ? I('post.from') : '2018-01-01';
        $to=I('post.to') ? I('post.to') : '2018-10-01';
        $child=I('post.child') ? I('post.child') : 0;
        $userModel=M('user');
        $userAll=$userModel->field('user_id,user_recommend,group,position')->where('(user_id='.$user['user_id'].') or ((user_role=1) and (user_recommend > 0))')->select();
        $childrenFile='Uploads/getChildsClass1/'.date('Ymd').'-'.$user['user_id'].'.txt';
        if(file_exists($childrenFile)){//判断更新缓存
            $children=file_get_contents($childrenFile);
            $children=unserialize($children);
        }else{
            set_time_limit(120);//程序执行时间
            $children= $this->getChildsClass1($userAll,$user['user_id'],[],0);//print_r($children);die;
            $childrenData=serialize($children);
            file_put_contents($childrenFile,$childrenData);
           // $this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
        }
        $login=[];
        $member=[];//【user_id】=》array()组装信息数据
        if(empty($children)){
            $this->error("为找到相关下线用户信息");
        }else{//过滤，筛选出当前账户的下线
            if(empty($child)){
                foreach ($children as $k => $v){
                    $login[]=$v['user_id'];
                    $member[$v['user_id']]=$v;
                }
            }else{
                $child=explode(',',$child);
                foreach ($children as $k => $v){
                    if(in_array($v['user_id'],$child)){
                        $login[]=$v['user_id'];
                        $member[$v['user_id']]=$v;
                    }
                }
            }
        }
        $section=C('section');//获取号段
        $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';

        if(!empty($from) && !empty($to)){
            $where.=' and (CLOSE_TIME between \''.$from.'\' and \''.$to.'\') ';
        }
        $where.=' and (right(SYMBOL,2) = \'bo\')';
        $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        if($user['type']==1){
//            $model = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }
        $reoups=$model->field('LOGIN,sum(VOLUME)')->where($where)->group('LOGIN')->select();
//        print_r($reoups);die;
        if(empty($reoups)){
            $this->error("未找到交易记录");
        }
        $group=M('mt4_groups')->field('mt4_group,ratio')->select();
        $ratio=[];//每个组别的佣金比率
        foreach ($group as $k => $v){
            $ratio[$v['mt4_group']]=$v['ratio'];
        }
        $list=[];//最终需要返佣的数据
        foreach ($reoups as $k => $v){
            if(in_array($v['login'],$login)){
                //unset($reoups[$k]);
                $v['ratio']=$ratio[$user['group']];
                $v['parent']=$user['user_id'];
                $v['money']=round($ratio[$user['group']]*round($v['sum(volume)']/100),2);
                $list[]=$v;
            }
        }
        $this->assign('list',$list);
        $this->display('summary');
        //$this->ajaxReturn(array('status'=>1,'msg'=>$list));
    }
    //获取IB返佣数据的父级
    public function getRebateParents($data,$user_recommend,$position,$arr){
        foreach($data as $k => $v){
            if($v['user_id']==$user_recommend){
                if($v['position']>1){
                    if($v['position']>=$position){
                        $arr[]=array('user_id'=>$v['user_id'],'position'=>$v['position'],'group'=>$v['group']);
                        unset($data[$k]);
                        $arr=$this->getRebateParents($data,$v['user_recommend'],$v['position'],$arr);
                    }else{
                        unset($data[$k]);
                        $arr=$this->getRebateParents($data,$v['user_recommend'],$position,$arr);
                    }
                }else{
                    unset($data[$k]);
                    $arr=$this->getRebateParents($data,$v['user_recommend'],$position,$arr);
                }
            }
        }
        return $arr;
    }
    //佣金汇总-2层佣金
    public function searchSummary2(){
        $user=session('user');
        if(empty($user['user_id'])){
            $this->ajaxReturn(array('status'=>0,'msg'=>'无效的登陆信息，请重新登陆'));
        }
        $from=I('post.from') ? I('post.from') : '2017-01-01';
        $to=I('post.to') ? I('post.to') : '2017-01-13';
        $child=I('post.child') ? I('post.child') : 0;
        $userModel=M('user');
        $userAll=$userModel->field('user_id,user_recommend,group,position')->where('(user_id='.$user['user_id'].') or ((user_role=1) and (user_recommend > 0))')->select();
        $childrenFile='Uploads/getChildsClass/'.date('Ymd').'-'.$user['user_id'].'.txt';
        if(file_exists($childrenFile)){//判断更新缓存
            $children=file_get_contents($childrenFile);
            $children=unserialize($children);
        }else{
            set_time_limit(120);//程序执行时间
            $children= $this->getChildsClass($userAll,$user['user_id'],[],0);//print_r($children);die;
            $childrenData=serialize($children);
            file_put_contents($childrenFile,$childrenData);
            $this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
        }
        //print_r($children);die;
        $login=[];
        $member=[];//【user_id】=》array()组装信息数据
        if(empty($children)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'为找到相关下线用户信息'));
        }else{//过滤，筛选出当前账户的下线
            if(empty($child)){
                foreach ($children as $k => $v){
                    $login[]=$v['user_id'];
                    $member[$v['user_id']]=$v;
                }
            }else{
                $child=explode(',',$child);
                foreach ($children as $k => $v){
                    if(in_array($v['user_id'],$child)){
                        $login[]=$v['user_id'];
                        $member[$v['user_id']]=$v;
                    }
                }
            }
        }
        $section=C('section');//获取号段
        $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';
        if(!empty($from) && !empty($to)){
            $where.=' and (CLOSE_TIME between \''.$from.'\' and \''.$to.'\') ';
        }
        $where.=' and (right(SYMBOL,2) = \'bo\')';
        $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        if($user['type']==1){
//            $model = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }
        $reoups=$model->field('LOGIN,sum(VOLUME)')->where($where)->group('LOGIN')->select();
        if(empty($reoups)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'未找到交易记录'));
        }
        $hasTradesUser=[];//有交易的用户信息
        foreach ($reoups as $k => $v){//筛选出有交易的用户信息
            if(in_array($v['login'],$login)){
                //unset($reoups[$k]);
                $v['volume']=intval($v['sum(volume)']/100);
                $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                $v['userInfo']=$member[$v['login']];
                $v['user_recommend']=$member[$v['login']]['user_recommend'];
                $hasTradesUser[]=$v;
            }
        }
        //$reoups=array_merge($reoups);
        print_r($hasTradesUser);die;
        $rebateData=[];//最终需要返佣的数据-明细
        set_time_limit(120);//程序执行时间
        foreach ($hasTradesUser as $k => $v){
            $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
            if(!empty($parents)){
                foreach ($parents as $k2 => $v2){
                    if($v2['user_id']==$user['user_id']){
                        $parents2=$parents;
                        foreach($parents2 as $ke => $va){
                            $flag=0;
                            foreach($parents as $key => $val){
                                if($va['position']==$val['position']){
                                    $flag++;
                                    if($flag>2){
                                        unset($parents[$key]);
                                    }
                                }
                            }
                        }
                        $v['parents']=$parents;//筛选出有返佣父级的数据
                        $rebateData[]=$v;break;
                    }
                }
            }
        }
        print_r($rebateData);die;
        if(empty($rebateData)){$this->ajaxReturn(array('status'=>0,'msg'=>'未获取到佣金信息'));}
        $position=M('position')->field('id,ratio')->select();
        $pos=[];
        foreach($position as $k => $v){
            $pos[$v['id']]=$v['ratio'];
        }
        foreach ($rebateData as $k => $v){
            foreach ($v['parents'] as $ke => $va){
                $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                if($ke>0){
                    $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                    if($ratio>0){
                        $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                    }else if($ratio==0){
                        $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=0;
                    }
                }else{
                    $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                }
            }
        }
        print_r($rebateData);
        if(empty($rebateData)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'未查找到相关佣金信息'));
        }else{
            $list=[];
            foreach ($rebateData as $k => $v){
                foreach ($v['parents'] as $key => $val){
                    if($v['parent']['user_id']==$user['user_id']){
                        $list[]=array(
                            'login'=>$v['user_id'],//交易用户
                            'agent'=>$val['user_id'],//受益人
                            'group'=>$val['group'],//受益人组别
                            'money'=>$val['money'],//佣金金额
                            'volume'=>$v['volume']//交易手数
                        );
                    }
                }
            }
        }
        print_r($list);die;
        $this->ajaxReturn(array('status'=>1,'msg'=>$list));
    }
    //佣金汇总-3层加外汇佣金
    public function searchSummary3(){
        $user=session('user');
        if(empty($user['user_id'])){
            //$this->ajaxReturn(array('status'=>0,'msg'=>'无效的登陆信息，请重新登陆'));
            $this->error("无效的登陆信息，请重新登陆",'summary');
        }
        $from=I('post.from') ? I('post.from') : '';
        $to=I('post.to') ? I('post.to') : '';
        $child=I('post.child') ? I('post.child') : 0;
        $userModel=M('user');
        $userAll=$userModel->field('user_id,user_recommend,group,position')->where('(user_id='.$user['user_id'].') or ((user_role=1) and (user_recommend > 0))')->select();
        $childrenFile='Uploads/getChildsClass/'.date('Ymd').'-'.$user['user_id'].'.txt';
        if(file_exists($childrenFile)){//判断更新缓存
            $children=file_get_contents($childrenFile);
            $children=unserialize($children);
        }else{
            set_time_limit(120);//程序执行时间
            $children= $this->getChildsClass($userAll,$user['user_id'],[],0);//print_r($children);die;
            $childrenData=serialize($children);
            file_put_contents($childrenFile,$childrenData);
            //$this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
        }
        //print_r($children);die;
        $login=[];
        $member=[];//【user_id】=》array()组装信息数据
        if(empty($children)){
            $this->error("未找到相关下线用户信息",'summary');
            //$this->ajaxReturn(array('status'=>0,'msg'=>'为找到相关下线用户信息'));
        }else{//过滤，筛选出当前账户的下线
            if(empty($child)){
                foreach ($children as $k => $v){
                    $login[]=$v['user_id'];
                    $member[$v['user_id']]=$v;
                }
            }else{
                $child=explode(',',$child);
                foreach ($children as $k => $v){
                    if(in_array($v['user_id'],$child)){
                        $login[]=$v['user_id'];
                        $member[$v['user_id']]=$v;
                    }
                }
            }
        }
        $section=C('section');//获取号段
        $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';
        if(!empty($from) && !empty($to)){
            $where.=' and (CLOSE_TIME between \''.$from.'\' and \''.$to.'\') ';
        }else{
            $this->error("时间不可为空",'summary');
        }
        $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        if($user['type']==1){
//            $model = M('mt4_trades', '', 'DB_CONFIG3');//数字
//        }else{
//            $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
//        }
        $reoups=$model->field('LOGIN,SYMBOL,sum(VOLUME)')->where($where)->group('LOGIN,SYMBOL')->select();
        if(empty($reoups)){
            $this->error("未找到交易记录",'summary');
           //$this->ajaxReturn(array('status'=>0,'msg'=>'未找到交易记录'));
        }
        $hasTradesUser=[];//有交易的用户信息
        foreach ($reoups as $k => $v){//筛选出有交易的用户信息
            if(in_array($v['login'],$login)){
                //unset($reoups[$k]);
                $v['volume']=intval($v['sum(volume)']/100);
                $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                $v['userInfo']=$member[$v['login']];
                $v['user_recommend']=$member[$v['login']]['user_recommend'];
                $hasTradesUser[]=$v;
            }
        }
        //品种点差
        $spreadData=M('symbol_spread')->field('id,symbol,spread')->select();
        $spread=[];
        foreach($spreadData as $k => $v){
            $spread[$v['symbol']]=$v['spread'];
        }
        $rebateData=[];//最终需要返佣的数据-明细
        foreach ($hasTradesUser as $k => $v){
            $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
            if(!empty($parents)){
                foreach ($parents as $k2 => $v2){
                    if($v2['user_id']==$user['user_id']){
                        $parents2=$parents;
                        foreach($parents2 as $ke => $va){
                            $flag=0;
                            foreach($parents as $key => $val){
                                if($va['position']==$val['position']){
                                    $flag++;
                                    if($flag>2){
                                        unset($parents[$key]);
                                    }
                                }
                            }
                        }
                        $v['spread']=$spread[$v['symbol']];
                        $v['parents']=$parents;//筛选出有返佣父级的数据
                        $rebateData[]=$v;break;
                    }
                }
            }
        }
        if(empty($rebateData)){
            $this->error("未获取到佣金信息",'summary');
            //$this->ajaxReturn(array('status'=>0,'msg'=>'未获取到佣金信息'));
        }
        $position=M('position')->field('id,ratio,ratio_foreign')->select();
        $pos=[];//返佣比率
        $foreign=[];//外用比率
        foreach($position as $k => $v){
            $pos[$v['id']]=$v['ratio'];
            $foreign[$v['id']]=$v['ratio_foreign'];
        }
        foreach ($rebateData as $k => $v){
            if(substr($v['symbol'],-2)=='bo'){
                foreach ($v['parents'] as $ke => $va){
                    $parent_arr[]=$va['user_id'];
                    $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                    if($ke>0){
                        $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                        if($ratio>0){
                            $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                        }else if($ratio==0){
                            $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                        }else{
                            $rebateData[$k]['parents'][$ke]['money']=0;
                        }
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                    }
                }
            }else{
                foreach ($v['parents'] as $ke => $va){
                    $parent_arr[]=$va['user_id'];
                    $rebateData[$k]['parents'][$ke]['ratio']=$foreign[$va['position']];
                    if($ke>0){
                        $ratio=$foreign[$va['position']]-$foreign[$v['parents'][$ke-1]['position']];
                        if($ratio>0){
                            $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume']*$v['spread'];
                        }else if($ratio==0){
                            $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                        }else{
                            $rebateData[$k]['parents'][$ke]['money']=0;
                        }
                    }else{
                        $rebateData[$k]['parents'][$ke]['money']=$foreign[$va['position']]*$v['volume']*$v['spread'];
                    }
                }
            }
        }
        //print_r($rebateData);
        $list=[];
        if(empty($rebateData)){
            //$this->ajaxReturn(array('status'=>0,'msg'=>'未查找到相关佣金信息'));
            $this->error("未查找到相关佣金信息",'summary');
        }else{
            foreach ($rebateData as $k => $v){
                foreach ($v['parents'] as $key => $val){
                    if($val['user_id']==$user['user_id']){
                        $list[]=array(
                            'login'=>$v['login'],//交易用户
							'symbol'=>$v['symbol'],
                            'agent'=>$val['user_id'],//受益人
                            'group'=>$val['group'],//受益人组别
                            'money'=>$val['money'],//佣金金额
                            'volume'=>$v['sum(volume)']//交易手数
                        );
                    }
                }
            }
        }

        $this->assign('list',$list);
        $this->display('summary');
        //$this->ajaxReturn(array('status'=>1,'msg'=>$list));
    }

    //外佣记录
    public function fdhsDebitList111111111(){
        $user=session('user');
        $model = M('fdhs_debit_log');
        $count = $model->where(['parent'=>$user['user_id']])->count();
        $Page = new \Think\Page($count,10);
        $show = $Page->show();
        $data = $model->field('id,login,money,volume,parent,time,status')->where(['parent'=>$user['user_id']])->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('data',$data);
        $this->assign('page',$show);
        $this->display();
    }
	
	public function fdhsDebitList(){
        $user=session('user');
        $model = M('mt4_trades', '', 'DB_CONFIG2');//外汇
		$where='(LOGIN='.$user['user_id'].') and (`COMMENT` like \'agent%\')';
        $count = $model->where($where)->count();
        $Page = new \Think\Page($count,10);
        $show = $Page->show();
        $data = $model->field('TICKET,LOGIN,CLOSE_TIME,PROFIT,COMMENT')->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('data',$data);
        $this->assign('page',$show);
        $this->display();
    }
	
	public function grantList(){//佣金发放
        $user=session('user');
        $from=I('post.from') ? I('post.from') : 0;
        $to=I('post.to') ? I('post.to') : 0;
        //查询佣金发放记录
        $model=M('mt4_trades','','DB_CONFIG2');
        $where='(CMD = 6) and (LOGIN = '.$user['user_id'].') and (COMMENT like \'CommBo%\')';
		if(!empty($from) && !empty($to)){
			$this->assign('from',$from);
			$this->assign('to',$to);
			$where.='and (CLOSE_TIME between \''.$from.'\' and \''.$to.' 23:59:59\') ';
		}
        $count = $model->where($where)->count();
        $Page = new \Think\Page($count,10);
        $show = $Page->show();
		$list=$model->field('TICKET,LOGIN,CLOSE_TIME,PROFIT,COMMENT')->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }
}